//
//  DrawProtocol.m
//  TabulaImaginarium11
//
//  Created by TA2 on 6/21/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DrawProtocol.h"

@implementation DrawProtocol

- (void)readPacket:(NSArray *)packet fromSocket:(AsyncSocket *)socket {
    
	NSArray *arguments = packet;
        /*NSLog(stringTag);
     if ([arguments count] > 1) { NSLog([arguments objectAtIndex:1]);}
     if ([arguments count] > 2) { NSLog([arguments objectAtIndex:2]);}
     if ([arguments count] > 3) { NSLog([arguments objectAtIndex:3]);}
     if ([arguments count] > 4) { NSLog([arguments objectAtIndex:4]);}
     if ([arguments count] > 5) { NSLog([arguments objectAtIndex:5]);}
     if ([arguments count] > 6) { NSLog([arguments objectAtIndex:6]);}
     if ([arguments count] > 7) { NSLog([arguments objectAtIndex:7]);}
    if ([arguments count] > 8) { NSLog([arguments objectAtIndex:8]);}
    if ([arguments count] > 9) { NSLog([arguments objectAtIndex:9]);}
    if ([arguments count] > 10) { NSLog([arguments objectAtIndex:10]);}
    if ([arguments count] > 11) { NSLog([arguments objectAtIndex:11]);}
    if ([arguments count] > 12) { NSLog([arguments objectAtIndex:12]);}
    if ([arguments count] > 13) { NSLog([arguments objectAtIndex:13]);}
    if ([arguments count] > 14) { NSLog([arguments objectAtIndex:14]);}*/
	if ([arguments count] > 1) {
		if ([[arguments objectAtIndex:1] isEqualToString:@"RAL"]) {
            if ([Players sharedLocalPlayer].isHost) {
				[self sendSuspend];
                NSArray *modifiedTiles = [contentView.backgroundView.map getAllModifiedTilePoints];
                for (NSValue *pointValue in modifiedTiles) {
                    CGPoint point = [pointValue CGPointValue];
                    for (int index = 0; index < 10; index++) {
                        for (Player *player in [Players sharedAllPlayers]) {
                            NSArray *paths = [contentView.drawingView.map getTilePathsAtPoint:point forPlayer:player forLayer:index];
                            if (paths) {
                                for (DrawingPath *path in paths) {
                                    [self sendLine:path forPlayer:player atLayer:index atPoint:point];
                                }
                            }
                        }
                    }
                }
				[self sendContinue];
			}
		} else if ([[arguments objectAtIndex:1] isEqualToString:@"SL"]) {
			if ([Players sharedLocalPlayer].isHost) {
				[[NetworkController sharedNetworkController] sendDataToAll:[NetworkController argumentArrayToData:arguments] withTag:0 butSocket:socket];
			}
			CGPoint point = (CGPoint){[[arguments objectAtIndex:4] intValue], [[arguments objectAtIndex:5] intValue]};
			NSMutableArray *paths = [[NSMutableArray alloc] init];
            int numberOfColorComponents = [[arguments objectAtIndex:8] intValue];
			for (int i = 9 + numberOfColorComponents; i < [arguments count] - 2; i += 2) {
				[paths addObject:[NSValue valueWithCGPoint:CGPointMake([((NSString *)[arguments objectAtIndex:i]) floatValue], [((NSString *)[arguments objectAtIndex:i+1]) floatValue])]];
			}
			DrawingPath *drawingPath = [[DrawingPath alloc] init];
			drawingPath.points = paths;
			drawingPath.lineWidth = [[arguments objectAtIndex:6] floatValue];
            drawingPath.colorTexturePath = [arguments objectAtIndex:7];
            if ([drawingPath.colorTexturePath isEqualToString:@"nil"]) {
                drawingPath.colorTexturePath = nil;
            } 
            if (drawingPath.colorTexturePath) {
                drawingPath.color = [UIColor colorWithPatternImage:[UIImage imageNamed:drawingPath.colorTexturePath]];
            } else {
                if (numberOfColorComponents == 2) {
                    drawingPath.color = [UIColor colorWithWhite:[[arguments objectAtIndex:9] floatValue] alpha:[[arguments objectAtIndex:10] floatValue]];
                    if ([[arguments objectAtIndex:9] floatValue] == 0 && [[arguments objectAtIndex:10] floatValue] == 0) {
                        drawingPath.color = [UIColor clearColor];
                    }
                } else if (numberOfColorComponents == 4) {
                    drawingPath.color = [UIColor colorWithRed:[[arguments objectAtIndex:9] floatValue] green:[[arguments objectAtIndex:10] floatValue] blue:[[arguments objectAtIndex:11] floatValue] alpha:[[arguments objectAtIndex:12] floatValue]];
                }
            }
			[contentView.drawingView.map addTilePath:drawingPath atPoint:point forPlayer:[Players playerWithIp:[arguments objectAtIndex:2]] forLayer:[[arguments objectAtIndex:3] intValue]];
            [drawingPath release];
			[contentView.drawingView setNeedsDisplayInRect:(CGRect){(CGPoint){point.x*contentView.drawingView.tileSize.width, point.y*contentView.drawingView.tileSize.height}, (CGSize){contentView.drawingView.tileSize.width, contentView.drawingView.tileSize.height}}];
		} else if ([[arguments objectAtIndex:1] isEqualToString:@"RS"]) {
            contentView.suspensionCount++;
            if (contentView.suspensionCount > 0) {
                [contentView disableUI];
            }
        } else if ([[arguments objectAtIndex:1] isEqualToString:@"RC"]) {
            contentView.suspensionCount--;
            if (contentView.suspensionCount == 0) {
                [contentView enableUI];
            }
        }
	}
}
- (void)sendRequestForAllLines {
	//RAL: Request all lines
	NSString *dataString = [[stringTag stringByAppendingString:@"|RAL"] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)sendLine:(DrawingPath *)line forPlayer:(Player *)player atLayer:(int)layer atPoint:(CGPoint)tilePoint {
    NSString *colorTexturePath = line.colorTexturePath;
    if (!colorTexturePath) {
        colorTexturePath = @"nil";
    }
	NSString *dataString = [stringTag stringByAppendingFormat:[[[[[[@"|SL|" stringByAppendingString:player.ip] stringByAppendingFormat:[NSString stringWithFormat:@"|%d", layer]]stringByAppendingString:[NSString stringWithFormat:@"|%f|%f|", tilePoint.x, tilePoint.y]] stringByAppendingFormat:[NSString stringWithFormat:@"%f|", line.lineWidth]] stringByAppendingString:colorTexturePath] stringByAppendingString:@"|"]];
    const CGFloat *components = CGColorGetComponents(line.color.CGColor);
    int numberOfComponents = CGColorGetNumberOfComponents(line.color.CGColor);
    dataString = [dataString stringByAppendingFormat:@"%d|", numberOfComponents];
    for (int i = 0; i < numberOfComponents; i++) {
        dataString = [dataString stringByAppendingFormat:@"%f|", components[i]];
    }
	for (int i = 0; i < line.points.count;i++) {
		CGPoint point = [((NSValue *)[line.points objectAtIndex:i]) CGPointValue];
		dataString = [dataString stringByAppendingString:[NSString stringWithFormat:@"%f|%f|", point.x, point.y]];
	}
	dataString = [dataString stringByAppendingFormat:@"≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)sendSuspend {
    //RS: Request suspended mode
	NSString *dataString = [[stringTag stringByAppendingString:@"|RS"] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)sendContinue {
    //RC: Request continue from suspended mode
	NSString *dataString = [[stringTag stringByAppendingString:@"|RC"] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)setupProtocol {
	if (![Players sharedLocalPlayer].isHost) {
		[self sendRequestForAllLines];
	}
}

@end
